package com.xxx.springboot.util;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;


/**
 * Cipher加密/解密工具
 */
public class CipherUtil {
	
	public static String DEFAULT_KEY = "abCDE@123"; // 默认key
	
	private static String CIPHER_ALGORITHM = "AES"; // optional value AES/DES/DESede

	/**
	 * 获取key
	 * @param strKey
	 * @return
	 */
	private static Key getKey(String key) {
		try {
			if (StringUtils.isEmpty(key)) {
				key = DEFAULT_KEY;
			}
			KeyGenerator generator = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(key.getBytes());
			generator.init(128, secureRandom);
			return generator.generateKey();
		} catch (Exception e) {
			throw new RuntimeException("初始化密钥出现异常 ");
		}
	}

	/**
	 * aes加密
	 * @param message
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String message, String key) throws Exception {
		SecureRandom sr = new SecureRandom();
		Key secureKey = getKey(key);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, secureKey, sr);
		byte[] bt = cipher.doFinal(message.getBytes());
		String strS = Base64.getEncoder().encodeToString(bt);
		return strS;
	}

	/**
	 * aes解密
	 * @param encryptMsg
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String encryptMsg, String key) throws Exception {
		SecureRandom sr = new SecureRandom();
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		Key secureKey = getKey(key);
		cipher.init(Cipher.DECRYPT_MODE, secureKey, sr);
		byte[] res = Base64.getDecoder().decode(encryptMsg);
		res = cipher.doFinal(res);
		return new String(res);
	}

	public static void main(String[] args) throws Exception {
		String message = "123456789012345aaa123456789012345123456789012345";
		System.out.println("message: " + message);
		String encryptMsg = encrypt(message, null);
		System.out.println("encrypted: " + encryptMsg);

		String decryptedMsg = decrypt(encryptMsg, "");
		System.out.println("decrypted: " + decryptedMsg);
	}
}
